package com.chb.controller;

import com.chb.filters.JwtUtils;
import com.chb.model.MyUserDetails;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author CHB
 * @createTime 2022-6-16 11:39
 */
@RestController
public class TestController {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private AuthenticationManager authenticationManager;

    @GetMapping("/login")
    public String login(@RequestParam("name") String name,@RequestParam("password") String password){
        // 密码校验，使用AuthenticationManager调用authenticate，间接通过UserDetailsService获取用户信息，最终在AuthenticationManager校验密码正确性
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(name, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate == null){
            return "error";
        }
        MyUserDetails principal = (MyUserDetails) authenticate.getPrincipal();
        System.out.println(principal.toString());
        // String s = jwtUtils.generateToken(userInfo);
        return principal.getUserInfo().toString();
    }

    @GetMapping("/get")
    public String get(){
        System.out.println("get");
        return "ok";
    }
}
